<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>给所有元素添加事件</title>
    <style>
        html,body {
           height: 100%;
        }
        .container {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100%;
            flex-wrap: wrap;
        }
        .container > span {
            display: inline-block;
            min-width: 50px;
            text-align: center;
            border: 1px solid #b2d2f1;
            color:#9f12e1;
            margin-right: 15px;
            padding: 10px 15px;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <div id="container" class="container">
        <span>1</span>
        <span>2</span>
        <span>3</span>
        <span>4</span>
    </div>
    <script>
        const addEventListenerAll = (targets, type, listener, options, useCapture) => Array.from(targets).forEach((
            target, index) => target.addEventListener(type, e => listener(e, index), options, useCapture));
        const container = document.getElementById("container");
        addEventListenerAll(container.children,"click",(e,index) => {
            alert(index + 1)
        })
    </script>
</body>

</html>